package com.huli.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huli.mapper.DepartmentMapper;
import com.huli.mapper.SysOrganizationMapper;
import com.huli.pojo.SysDepartment;
import com.huli.pojo.SysOrganization;
import com.huli.service.DepartmentService;
import com.huli.vo.DepartmentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private SysOrganizationMapper sysOrganizationMapper;

    @Override
    public DepartmentVo departmentList(DepartmentVo departmentVo) {
        // 使用PageHelper插件进行分页
        PageHelper.startPage(departmentVo.getPageNum(), departmentVo.getPageSize());
        // 调用departmentMapper的DepartmentList方法，获取部门列表
        List<SysDepartment> sysDepartments = departmentMapper.DepartmentList(departmentVo);
        // 调用sysOrganizationMapper的OrganizationList方法，获取组织列表
        List<SysOrganization> sysOrganizations = sysOrganizationMapper.OrganizationList();
        
        // 遍历部门列表
        for (SysDepartment sysDepartment : sysDepartments) {
            // 遍历组织列表，找到匹配的组织
            for (SysOrganization sysOrganization : sysOrganizations) {
                // 假设部门和组织通过orgId关联，需要确保实体类中有这个字段
                if (sysDepartment.getOrgId().equals(sysOrganization.getId())) {
                    sysDepartment.setOrgName(sysOrganization.getOrgName());
                    break; // 找到匹配的组织后立即退出内层循环
                }
            }
        }
        
        // 将部门列表封装到PageInfo对象中
        PageInfo<SysDepartment> pageInfo = new PageInfo<>(sysDepartments);
        // 返回封装了分页信息和部门列表的DepartmentVo对象
        return new DepartmentVo(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    // 重写父类方法，删除指定id的部门
    public void deleteDepartment(Long id) {
        // 调用departmentMapper中的deleteDepartment方法，删除指定id的部门
        departmentMapper.deleteDepartment(id);
    }

    @Override
    // 重写父类方法，添加部门
    public void addDepartment(SysDepartment sysDepartment) {
        // 调用departmentMapper的addDepartment方法，添加部门
        departmentMapper.addDepartment(sysDepartment);
    }

    @Override
    // 重写updateDepartment方法
    public void updateDepartment(SysDepartment sysDepartment) {
        // 调用departmentMapper的updateDepartment方法，更新部门信息
        departmentMapper.updateDepartment(sysDepartment);
    }

    @Override
    // 重写父类方法，查询部门名称
    public List<SysDepartment> queryDepartmentName() {
        // 调用departmentMapper中的queryDepartmentName方法，返回部门名称列表
        return departmentMapper.queryDepartmentName();
    }

    @Override
    // 重写父类方法，根据id查询部门信息
    public SysDepartment queryDepartmentById(Long id) {
        // 调用departmentMapper的queryDepartmentById方法，根据id查询部门信息
        return departmentMapper.queryDepartmentById(id);
    }
}